import RootContainer from "../using/root-container";
import RootContainerConfig from "../using/typing/root-container-config";
import FieldConfig, {ElementType} from "../using/typing/field-config";
import DyForm from "../DyForm";
import {AddEleEvent, FormDesign} from "./form-design";
import InputFormElementDesign from "./form-elements/input-form-element-design";
import FormElement from "../using/typing/form-element";
import SelectFormElementDesign from "./form-elements/select-form-element-design";
import {merge} from "lodash-es";
import {FormElementDesign} from "./form-elements/form-element-design";
import {ElementDetail} from "./form-element-detail/element-detail";
import {ElementDetailDesign} from "./element-detail-design";

/**
 * 与 {@link RootContainer} 大部分都一样的，多出以下2点
 * 1. 多出左右设计器
 * 2. 每个元素周围都多出设计器相关的按钮，如删除，拖动的手柄
 */
export default class RootContainerDesign extends RootContainer {

    private formDesign;
    private readonly elementDesign: ElementDetailDesign
    constructor(config: RootContainerConfig, fieldConfigs: FieldConfig[], form: DyForm) {
        super(config, fieldConfigs, form);
        this.formDesign = new FormDesign(form)
        this.formDesign.addEleEventListener((ev) => {
            this.addFormEleEvent(ev)
        })
        this.elementDesign = new ElementDetailDesign(form)
    }

    getFormConfigEl(): HTMLDivElement {
        return this.formDesign.getEl()
    }

    getElementConfigEl(): HTMLDivElement {
        return this.elementDesign.getEl()
    }

    addFormEleEvent(ev: AddEleEvent) {
        super.addConfig({
            type: ev.type,
            width: 1,
            name: 'New',
            inputType: 'text',
            defaultValue:''
        })
    }

    protected makeEle(conf: FieldConfig): FormElement<any> {
        if (conf.type === ElementType.INPUT) {
            return  new InputFormElementDesign(conf, this.config.elementHeight, this.form, this)
        } else if (conf.type === ElementType.SELECT) {
            return  new SelectFormElementDesign(conf, this.config.elementHeight, this.form, this)
        } else {
            throw new Error(`Not support type: ${conf.type}`)
        }
    }


    public getConfig() {
        return merge({}, this.config)
    }

    // 导出配置
    public getFieldConfigs() {
        return this.fieldConfigs.map(value => {
            return merge({}, value)
        })
    }
    // TODO
    //  1. 1个设计器
    showElementConfig(el: ElementDetail) {
        this.elementDesign.changeElementDetail(el)
    }
}
